<template>
  <div v-if="selectPlatform == 2">
    <div
      class="gva-search-box"
    >
      <el-form
        ref="elSearchFormRef"
        :inline="true"
        :model="searchInfo"
        class="demo-form-inline"
        :rules="searchRule"
      >
        <el-form-item>
          <el-input
            v-model="searchInfo.projectId"
            placeholder="项目ID"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="search"
            @click="onSubmit"
          >查询</el-button>
          <el-button
            icon="refresh"
            @click="onReset"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button
          type="primary"
          icon="plus"
          @click="openDialog"
        >新增</el-button>
      </div>
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        border
        row-key="id"
      >
        <el-table-column
          align="left"
          label="ID"
          prop="id"
          width="100"
        />
        <el-table-column
          align="left"
          label="账户名称"
          prop="account_name"
        />
        <el-table-column
          align="left"
          label="账户ID"
          prop="account_id"
        />
        <el-table-column
          align="left"
          label="项目ID"
          prop="project_id"
        />
        <el-table-column
          align="left"
          label="关键行为"
          prop="burial_flag"
        />
        <el-table-column
          align="left"
          label="AB测状态"
        >
          <template #default="scope">
            {{ scope.row.status == 1 ? '关闭' : '进行中' }}
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="ECPM"
          prop="ecpm"
          width="100"
        />
        <el-table-column
          align="left"
          label="设置次数"
          prop="setting_number"
          width="100"
        />
        <el-table-column
          align="left"
          label="创建时间"
          prop="created_at"
        />
        <el-table-column
          align="left"
          label="操作"
          fixed="right"
          min-width="100"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="edit"
              class="table-button"
              @click="updateqmReportAccountFunc(scope.row)"
            >变更</el-button>
            <el-button
              type="primary"
              link
              icon="delete"
              @click="deleteRow(scope.row)"
            >删除</el-button>
            <el-button
              type="primary"
              link
              icon="search"
              @click="abTest(scope.row)"
            >AB测</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :before-close="closeDialog"
      :title="type==='create'?'添加':'修改'"
      destroy-on-close
    >
      <el-scrollbar height="400px">
        <el-form
          ref="elFormRef"
          :model="formData"
          label-position="right"
          :rules="rule"
          label-width="100px"
        >
          <el-form-item
            label="账户名称:"
            prop="account_name"
          >
            <el-input
              v-model="formData.account_name"
              :clearable="true"
              placeholder="请输入账户名称"
            />
          </el-form-item>
          <el-form-item
            label="账户ID:"
            prop="account_id"
          >
            <el-input
              v-model="formData.account_id"
              :disabled="type=='update' ? true : false"
              :clearable="true"
              placeholder="请输入账户ID"
            />
          </el-form-item>
          <el-form-item
            label="项目ID:"
            prop="project_id"
          >
            <el-input
              v-model="formData.project_id"
              :clearable="true"
              :disabled="type=='update' ? true : false"
              placeholder="请输入项目ID"
            />
          </el-form-item>
          <el-form-item
            label="关键行为:"
            prop="burial_flag"
          >
            <el-select
              v-model="formData.burial_flag"
              style="width: 25%;"
              @change="selectBurial"
            >
              <el-option
                v-for="item in burialOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span style="padding-left: 10px;color: red;">
              请勿随意切换埋点事件
            </span>
          </el-form-item>
          <el-form-item
            label="ECPM:"
            prop="ecpm"
          >
            <el-input-number
              v-model="formData.ecpm"
              :clearable="true"
              placeholder="请输入ECPM"
            />
          </el-form-item>
          <el-form-item
            label="设置次数:"
            prop="setting_number"
          >
            <el-input
              v-model.number="formData.setting_number"
              :clearable="true"
              placeholder="请输入设置次数"
              :disabled="isActive"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createQmReportAccount,
  deleteQmReportAccount,
  updateQmReportAccount,
  findQmReportAccount,
  getQmReportAccountList
} from '@/api/qmReportAccount'

import {
  getQmBurialList
} from '@/api/qmBurial'

import { getUserGameList } from '@/api/qmGameList'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

defineOptions({
  name: 'QmReportAccount'
})

const gameHash = ref('')
const gameList = ref([])

const router = useRouter()

const getGameList = async() => {
  const res = await getUserGameList()
  if (res.code === 0) {
    gameList.value = res.data.gameList
  }
}

getGameList()

const selectGame = (val) => {
  gameHash.value = val
}

const isActive = ref(false)

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  gameHash: '',
  account_name: '',
  account_id: '',
  project_id: '',
  burial_flag: '',
  ecpm: 0,
  setting_number: 0
})

// 验证规则
const rule = reactive({
  account_name: [
    { required: true, message: '请输入账户名称', trigger: 'blur' }
  ],
  account_id: [
    { required: true, message: '请输入账户ID', trigger: 'blur' }
  ],
  project_id: [
    { required: true, message: '请输入项目ID', trigger: 'blur' }
  ],
  ecpm: [
    { required: true, message: '请输入ECPM', trigger: 'blur' }
  ],
  setting_number: [
    { required: true, message: '请输入设置次数', trigger: 'blur' }
  ],
  burial_flag: [
    { required: true, message: '请选择渠道', trigger: 'blur' }
  ]
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

const selectPlatform = ref(1)
const isPlatform = () => {
  const platform = localStorage.getItem('platform')
  if (platform == 0 || platform == '' || platform == null || platform == undefined) {
    ElMessage({
      type: 'error',
      message: '请先选择渠道'
    })
    selectPlatform.value = 1
    // setTimeout(() => {
    //   window.location.href = '/#/layout/dashboard'
    // }, 1000)
  } else {
    selectPlatform.value = 2
  }
}

isPlatform()

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

const selectBurial = (val) => {
  let flag = ''
  for (let i = 0; i < burialOption.value.length; i++) {
    if (burialOption.value[i].value == val) {
      flag = burialOption.value[i].label
    }
  }

  if (flag == '激活') {
    isActive.value = true
    formData.value.setting_number = 1
  } else {
    isActive.value = false
  }
}

const abTest = (row) => {
  router.push({ name: 'abTest', query: { id: row.id }})
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const burialOption = ref([])
const getBurialData = async() => {
  const arr = ['showAD','ViewOverAD','active','duration']
  const table = await getQmBurialList({ page: 1, pageSize: 999 })
  if (table.code === 0) {
    table.data.list.forEach(item => {
      if(arr.indexOf(item.flag)>=0)
        burialOption.value.push({
          label: item.name,
          value: item.id
        })
    })
  }
}

getBurialData()

// 查询
const getTableData = async() => {
  const table = await getQmReportAccountList({ page: page.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============
const platformOptions = ref([])
// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
  platformOptions.value = await getDictFunc('platform')
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteqmReportAccountFunc(row)
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateqmReportAccountFunc = async(row) => {
  const res = await findQmReportAccount({ id: row.id })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data

    // 把字符串转成int
    formData.value.burial_flag = parseInt(res.data.burial_flag)
    let flag = ''
    for (let i = 0; i < burialOption.value.length; i++) {
      if (burialOption.value[i].value == res.data.burial_flag) {
        flag = burialOption.value[i].label
      }
    }

    if (flag == '激活') {
      isActive.value = true
    } else {
      isActive.value = false
    }
    dialogFormVisible.value = true
  }
}

// 删除行
const deleteqmReportAccountFunc = async(row) => {
  const res = await deleteQmReportAccount({ id: row.id })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    gameHash: '',
    account_name: '',
    account_id: '',
    project_id: '',
    burial_flag: '',
    ecpm: 0,
    setting_number: 0
  }
}
// 弹窗确定
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res

    formData.value.gameHash = gameHash.value
    switch (type.value) {
      case 'create':
        res = await createQmReportAccount(formData.value)
        break
      case 'update':
        res = await updateQmReportAccount(formData.value)
        break
      default:
        res = await createQmReportAccount(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

</script>

<style>

</style>
